package com.qianniu.napi.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.FantimeType;
import com.qianniu.napi.admin.entity.penum.IotypeEnum;
import com.qianniu.napi.admin.entity.penum.JftypeEnum;
import com.qianniu.napi.admin.entity.penum.XffanType;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 积分表
 * </p>
 *
 * @author chenxuebin
 * @since 2018-09-04
 */
@RestController
public class JifenController {

    private static final Logger logger = LoggerFactory.getLogger(JifenController.class);

    @Autowired
    private IJifenService jifenService;
    @Autowired
    private IJifenFlowService jifenFlowService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IUserService userService;

    @RequestMapping("/api/jifen/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        page = jifenService.selectPage(page, new EntityWrapper<Jifen>()
                .eq("uid", ObjectUtil.getUid())
                .eq("state", 1));
        info.setInfo(page.getRecords());
        return info;
    }

    @RequestMapping("/api/jifen/gaikuang")
    @ResponseBody
    public Jinfo gaikuang() {
        Jinfo info = new Jinfo();
        // 字段校验
        Long uid = ObjectUtil.getUid();
        Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid",uid));
        Map<String,Object> map = new HashMap<String,Object>();

        FanConfig fconfig = redisService.getFanconfig(ObjectUtil.getMpid());
        MerchantConfig mconfig = redisService.getMconfig();

        map.put("total",jifen==null?0:jifen.getTotal());
        map.put("qiandao",fconfig.getSignfanMount()==null?0:fconfig.getSignfanMount().intValue());
        map.put("bindphone",fconfig.getShoujifanMount()==null?0:fconfig.getShoujifanMount().intValue());
        map.put("zhuanfa",fconfig.getZffanMount()==null?0:fconfig.getZffanMount().intValue());
        map.put("yuedu",fconfig.getReadfanMount()==null?0:fconfig.getReadfanMount().intValue());
        map.put("gouwu","0");//即将废弃
        map.put("xinyonghu",fconfig.getNuserfanMount()==null?0:fconfig.getNuserfanMount().intValue());
        info.setExtra(map);

        List<JifenFlow> jflist = jifenFlowService.selectList(new EntityWrapper<JifenFlow>()
                .setSqlSelect("id,num,jftype,iotype,createtime,uid")
                .eq("uid",uid)
                .eq("state",1)
                .eq("is_confirm",1)
                .orderBy("id",false));

        logger.info("----------------------------------------------------------------------------gaikuang mconfig.getJifenname()="+mconfig.getJifenname());
        if(!Strings.isNullOrEmpty(mconfig.getJifenname())){
            for(JifenFlow item:jflist){
                item.setJftypename(item.getJftypename().replace("积分",mconfig.getJifenname()));
            }
        }
        info.setInfo(jflist);

        return info;
    }

    @RequestMapping("/api/jifen/add")
    @ResponseBody
    public Jinfo jifenAdd(@Valid Jifen jifen, HttpServletRequest req) {
        Jinfo info = new Jinfo();
        // 字段校验
        jifen.setCreatetime(new Date());
        jifen.setFanliing(new BigDecimal(0));
        jifen.insert();
        return info;
    }

    @RequestMapping("/api/jifen/zengsong")
    @ResponseBody
    public Jinfo zengsong(String phone,Integer num) {
        Jinfo info = new Jinfo();
        if(Strings.isNullOrEmpty(phone)){
            info.setCode(4);
            info.setInfo("手机号参数有误");
            return info;
        }
        if(num==null||num<1){
            info.setCode(4);
            info.setInfo("积分参数有误");
            return info;
        }

        Long uid = ObjectUtil.getUid();
        User user = userService.selectOne(new EntityWrapper<User>()
                .setSqlSelect("id,is_mch isMch,is_platform isPlatform,is_agent isAgent,is_admin isAdmin,is_member isMember,member_level memberLevel")
                .eq("id",uid));

        User tuser = userService.selectOne(new EntityWrapper<User>()
                .setSqlSelect("id,is_mch isMch,is_platform isPlatform,is_agent isAgent,is_admin isAdmin,is_member isMember,member_level memberLevel")
                .eq("phone",phone).eq("mpid",ObjectUtil.getMpid()));
        if(tuser==null){
            info.setCode(1);
            info.setInfo("目标用户不存在或者该用户没有绑定手机号");
            return info;
        }
        if(uid.intValue()==tuser.getId().intValue()){
            info.setCode(1);
            info.setInfo("自己无法给自己充值积分");
            return info;
        }
//        if(user.getIsPlatform()==1&&tuser.getIsMch()!=1){
//            info.setCode(1);
//            info.setInfo("平台用户只能给商户赠送积分");
//            return info;
//        }
         if(user.getIsMch()==1&&(tuser.getIsMch()==1||tuser.getIsPlatform()==1)){
            info.setCode(1);
            info.setInfo("商家只能给用户赠送积分");
            return info;
        }else if(user.getIsPlatform()!=1&&user.getIsMch()!=1){
            info.setCode(1);
            info.setInfo("当前用户无权限赠送赠送积分");
            return info;
        }

        Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid",user.getId()));
        if(user.getIsMch()==1&&(jifen==null||jifen.getTotal().intValue() < num)){
            info.setCode(1);
            info.setInfo("当前赠送积分不够赠送额度");
            return info;
        }
        String sn = StringUtil.getSnNo("JF");
        // 赠送者减少积分
        jifenService.addJifenFlow(ObjectUtil.getUid(), ObjectUtil.getMid(), ObjectUtil.getMpid(),
                new BigDecimal(num), true, FantimeType.now.getVal(),
                sn, IotypeEnum.output, JftypeEnum.gift, "", 0l);

        // 被赠送者增加积分
        jifenService.addJifenFlow(tuser.getId(), ObjectUtil.getMid(), ObjectUtil.getMpid(),
                new BigDecimal(num), true, FantimeType.now.getVal(),
                sn, IotypeEnum.input, JftypeEnum.gift, "", 0l);

        return info;
    }

    @RequestMapping("/api/jifen/txlist")
    @ResponseBody
    public Jinfo txlist(
            @RequestParam(value = "shenhe", required = false) Integer shenhe,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize,
                        HttpServletRequest req) {
        Jinfo json = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Long uid = ObjectUtil.getUid();
        Page page = new Page(pageIndex, pageSize);

        Wrapper<JifenFlow> entity = new EntityWrapper<JifenFlow>()
                .eq("is_confirm", 1)
                .eq("jftype", JftypeEnum.duihuantx.getVal())
                .eq("mpid", ObjectUtil.getMpid())
                .eq("iotype", -1);
        if(shenhe==null||shenhe==0) entity.eq("uid", uid);

        entity.orderBy("id", false);
        page = jifenFlowService.selectPage(page, entity);

        json.setInfo(page.getRecords());
        return json;
    }

    @RequestMapping("/api/jifen/modify")
    @ResponseBody
    public Jinfo jifenUpdate(HttpServletRequest req,
                             Jifen jifen) {
        Jinfo info = new Jinfo();
        jifen.setModifytime(new Date());
        jifen.updateById();
        return info;
    }

    @RequestMapping("/api/jifen/detail")
    @ResponseBody
    public Jinfo getJifenDetailById(@RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        Jifen jifen = jifenService.selectById(id);
        info.setInfo(jifen);
        return info;
    }
}
